<template>
  <div class="page-container">
    <div class="page-header">
      <Button type="link" class="back-button" @click="handleGoBack">
        <arrow-left-outlined />
        返回列表
      </Button>
      <h2 class="page-title">{{ isEdit ? "编辑学校" : "新增学校" }}</h2>
    </div>

    <Card class="form-card">
      <Spin :spinning="loading">
        <Form
          ref="formRef"
          :model="formState"
          :rules="rules"
          v-bind="formLayout"
          layout="horizontal"
          :hide-required-mark="true"
        >
          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="学校名称" name="xxmc">
                <AutoComplete
                  v-model:value="formState.xxmc"
                  :options="schoolNameOptions"
                  :loading="schoolNameLoading"
                  allowClear
                  placeholder="请输入学校名称"
                  @search="handleSchoolNameSearch"
                  @select="handleSchoolNameSelect"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="学校地址" name="dz">
                <Input
                  v-model:value="formState.dz"
                  allowClear
                  placeholder="请输入学校地址"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="联系电话" name="lxdh">
                <Input
                  v-model:value="formState.lxdh"
                  allowClear
                  placeholder="请输入联系电话"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="地市" name="ds">
                <Select
                  v-model:value="formState.ds"
                  :options="cityOptions"
                  :loading="cityLoading"
                  allowClear
                  placeholder="请选择地市"
                  @change="handleCityChange"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="区县" name="qx">
                <Select
                  v-model:value="formState.qx"
                  :options="countyOptions"
                  :loading="countyLoading"
                  :disabled="!formState.ds"
                  allowClear
                  placeholder="请选择区县"
                  @change="handleCountyChange"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="乡镇（街道）" name="jd">
                <Select
                  v-model:value="formState.jd"
                  :options="townOptions"
                  :loading="townLoading"
                  :disabled="!formState.qx"
                  allowClear
                  placeholder="请选择乡镇（街道）"
                  @change="handleTownChange"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="社区（村）" name="sq">
                <Select
                  v-model:value="formState.sq"
                  :options="villageOptions"
                  :loading="villageLoading"
                  :disabled="!formState.jd"
                  allowClear
                  placeholder="请选择社区（村）"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="学校类型" name="xxlx">
                <Select
                  v-model:value="formState.xxlx"
                  placeholder="请选择学校类型"
                  allowClear
                >
                  <Select.Option
                    v-for="type in schoolTypes"
                    :key="type"
                    :value="type"
                  >
                    {{ type }}
                  </Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="经度" name="jd1">
                <InputNumber
                  v-model:value="formState.jd1"
                  style="width: 100%"
                  placeholder="请输入经度"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="纬度" name="wd">
                <InputNumber
                  v-model:value="formState.wd"
                  style="width: 100%"
                  placeholder="请输入纬度"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="学生人数规模" name="xsrsgm">
                <Input
                  v-model:value="formState.xsrsgm"
                  allowClear
                  placeholder="请输入学生人数规模"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="上学高峰时段" name="sxgfsd">
                <TimeRangePicker
                  v-model:value="formState.sxgfsd"
                  format="HH:mm"
                  valueFormat="HH:mm"
                  :placeholder="['开始时间', '结束时间']"
                  style="width: 100%"
                  allowClear
                />
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="下学高峰时段" name="xxgfsd">
                <TimeRangePicker
                  v-model:value="formState.xxgfsd"
                  format="HH:mm"
                   valueFormat="HH:mm"
                  :placeholder="['开始时间', '结束时间']"
                  style="width: 100%"
                  allowClear
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="接送管控类别" name="jsgklb">
                <Select
                  v-model:value="formState.jsgklb"
                  placeholder="请选择接送管控类别"
                  allow-clear
                >
                  <Select.Option
                    v-for="type in schoolControlTypes"
                    :key="type"
                    :value="type"
                  >
                    {{ type }}
                  </Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="责任中队" name="zrzd">
                <Input
                  v-model:value="formState.zrzd"
                  allowClear
                  placeholder="请输入责任中队"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="中队负责人" name="zdfzr">
                <Input
                  v-model:value="formState.zdfzr"
                  allowClear
                  placeholder="请输入中队负责人"
                />
              </Form.Item>
            </Col>
          </Row>

          <Row :gutter="24">
            <Col :span="12">
              <Form.Item label="负责人联系电话" name="fzrlxdh">
                <Input
                  v-model:value="formState.fzrlxdh"
                  allowClear
                  placeholder="请输入负责人联系电话"
                />
              </Form.Item>
            </Col>
            <Col :span="12">
              <Form.Item label="是否上传秩序管控方案" name="sfsczxgkfa">
                <Select
                  v-model:value="formState.sfsczxgkfa"
                  placeholder="请选择是否上传秩序管控方案"
                  allowClear
                >
                  <Select.Option value="1">是</Select.Option>
                  <Select.Option value="0">否</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>

          <Form.Item :wrapper-col="{ span: 24 }" class="form-actions">
            <Button type="primary" @click="handleSubmit" class="action-button"
              >提交</Button
            >
            <!-- <Button
              type="default"
              @click="handleSaveDraft"
              class="action-button"
              >保存为草稿</Button
            > -->
            <Button @click="handleCancel">取消</Button>
          </Form.Item>
        </Form>
      </Spin>
    </Card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watchEffect } from "vue";
import { useRouter, useRoute } from "vue-router";
import {
  Card,
  Form,
  Input,
  Select,
  InputNumber,
  Button,
  message,
  Spin,
  Row,
  Col,
  AutoComplete,
  TimeRangePicker,
} from "ant-design-vue";
import { ArrowLeftOutlined } from "@ant-design/icons-vue";
import { schoolApi } from "../api/schoolApi";
import { cityCodeMap, schoolTypes, schoolControlTypes } from "../types/school";
import city from "@/area/city.json";
import county from "@/area/county.json";
import town from "@/area/town.json";
import village from "@/area/village.json";
import Api from "@/api/school.js";
import { useSchoolStore } from "../stores/schoolStore";
import { debounce } from "lodash-es";

const router = useRouter();
const route = useRoute();
const schoolStore = useSchoolStore();

// 表单引用
const formRef = ref();

// 是否是编辑模式
const isEdit = ref(!!route.params.id);

// 加载状态
const loading = ref(false);

// 表单数据
const formState = reactive<any>({
  xxmc: "",
  dz: "",
  lxdh: "",
  ds: undefined,
  qx: undefined,
  jd: undefined,
  sq: undefined,
  xxlx: undefined,
  jd1: 0,
  wd: 0,
  xsrsgm: "",
  sxgfsd: [],
  xxgfsd: [],
  jsgklb: undefined,
  isDraft: false,
  zrzd: "",
  zdfzr: "",
  fzrlxdh: "",
  sfsczxgkfa: '1',
});

// 表单布局
const formLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

// 表单验证规则
const rules = {
  xxmc: [{ required: true, message: "请输入学校名称" }],
  dz: [{ required: true, message: "请输入学校地址" }],
  ds: [{ required: true, message: "请选择地市" }],
  qx: [{ required: false }],
  jd: [{ required: false }],
  sq: [{ required: false }],
  xxlx: [{ required: true, message: "请选择学校类型" }],
  jd1: [
    { required: true, message: "请输入经度" },
    {
      pattern: /^\d+\.\d{6,}$/,
      message: "经度必须为数字且小数位数不能低于6位",
    },
  ],
  wd: [
    { required: true, message: "请输入纬度" },
    {
      pattern: /^\d+\.\d{6,}$/,
      message: "纬度必须为数字且小数位数不能低于6位",
    },
  ],
  xsrsgm: [
    { required: true, message: "请输入学生人数规模" },
    { pattern: /^\d+$/, message: "学生人数规模只能输入数字" },
  ],
  sxgfsd: [
    {
      validator: (rule: any, value: any) => {
        if (!value || !Array.isArray(value) || value.length !== 2) {
          return Promise.reject('请选择完整的时间范围');
        }
        if (!value[0] || !value[1]) {
          return Promise.reject('请选择完整的时间范围');
        }
        return Promise.resolve();
      }
    }
  ],
  xxgfsd: [
    {
      validator: (rule: any, value: any) => {
        if (!value || !Array.isArray(value) || value.length !== 2) {
          return Promise.reject('请选择完整的时间范围');
        }
        if (!value[0] || !value[1]) {
          return Promise.reject('请选择完整的时间范围');
        }
        return Promise.resolve();
      }
    }
  ],
  jsgklb: [{ required: true, message: "请选择接送管控类别" }],
  lxdh: [
    { required: false },
    {
      pattern: /^(1[3-9]\d{9}|0\d{2,3}-\d{7,8})$/,
      message: "请输入正确的手机号码或固定电话号码（固定电话格式：区号-号码）",
    },
  ],
  zrzd: [{ required: true, message: "请输入责任中队" }],
  zdfzr: [{ required: true, message: "请输入中队负责人" }],
  fzrlxdh: [
    { required: true, message: "请输入负责人联系电话" },
    {
      pattern: /^(1[3-9]\d{9}|0\d{2,3}-\d{7,8})$/,
      message: "请输入正确的手机号码或固定电话号码（固定电话格式：区号-号码）",
    },
  ],
  sfsczxgkfa: [{ required: true, message: "请选择是否上传秩序管控方案" }],
};

// 下拉选项数据
const cityOptions = ref<any[]>(
  city.map((e) => ({ value: e.code, label: e.name }))
);
const countyOptions = ref<any[]>([]);
const townOptions = ref<any[]>([]);
const villageOptions = ref<any[]>([]);

watchEffect(() => {
  countyOptions.value = county
    .filter((item) => item.c_code === formState.ds)
    .map((item) => ({
      label: item.name,
      value: item.code,
    }));
  console.log(countyOptions);
});
watchEffect(() => {
  townOptions.value = town
    .filter((item) => item.c_code === formState.qx)
    .map((item) => ({
      label: item.name,
      value: item.code,
    }));
});
watchEffect(() => {
  villageOptions.value = village
    .filter((item) => item.t_code === formState.jd)
    .map((item) => ({
      label: item.name,
      value: item.code,
    }));
});

// 加载状态
const cityLoading = ref(false);
const countyLoading = ref(false);
const townLoading = ref(false);
const villageLoading = ref(false);

// 处理地市变化
const handleCityChange = (value: string) => {
  formState.qx = undefined;
  formState.jd = undefined;
  formState.sq = undefined;
};
// 处理区县变化
const handleCountyChange = (value: string) => {
  formState.jd = undefined;
  formState.sq = undefined;
};
// 处理乡镇变化
const handleTownChange = (value: string) => {
  formState.sq = undefined;
};

// 提交表单
const handleSubmit = () => {
  console.log(formState);

  formRef.value.validate().then(async () => {
    loading.value = true;
    try {

      const submitData = {
        ...formState,
        sxgfsd: formState.sxgfsd.join('-'),
        xxgfsd: formState.xxgfsd.join('-'),
      };

      if (isEdit.value) {
        const params = {
          ds:
            cityOptions.value.find((e) => e.value === formState.ds)?.label ||
            formState.ds,
          dsCode:
            cityOptions.value.find((e) => e.value === formState.ds)?.value ||
            formState.dsCode,
          qx:
            countyOptions.value.find((e) => e.value === formState.qx)?.label ||
            formState.qx,
          jd:
            townOptions.value.find((e) => e.value === formState.jd)?.label ||
            formState.jd,
          sq:
            villageOptions.value.find((e) => e.value === formState.sq)?.label ||
            formState.sq,
        };
        // 更新学校
        await Api.edit({ ...submitData, ...params });
        message.success("更新学校成功");
      } else {
        // 添加学校
        submitData.isDraft = false;
        const params = {
          ds: cityOptions.value.find((e) => e.value === formState.ds)?.label,
          dsCode: formState.ds,
          qx: countyOptions.value.find((e) => e.value === formState.qx)?.label,
          jd: townOptions.value.find((e) => e.value === formState.jd)?.label,
          sq: villageOptions.value.find((e) => e.value === formState.sq)?.label,
        };
        console.log("params", params);

        await Api.add({ ...submitData, ...params });
        message.success("添加学校成功");
      }
      router.push("/schools");
    } catch (error) {
      console.log(error);
    } finally {
      loading.value = false;
    }
  });
};

// 保存为草稿
const handleSaveDraft = async () => {
  // 不进行表单验证，直接保存当前状态
  loading.value = true;
  try {
    formState.isDraft = true;
    if (isEdit.value) {
      await schoolApi.updateSchool(formState);
      message.success("草稿保存成功");
    } else {
      await schoolApi.addSchool(formState);
      message.success("草稿保存成功");
    }
    router.push("/schools");
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message);
    } else {
      message.error("保存草稿失败");
    }
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  router.push("/schools");
};

// 返回主页
const handleGoBack = () => {
  router.push("/schools");
};

// 在组件挂载时，如果是编辑模式则加载学校数据
onMounted(() => {
  const id = route.params.id as string;
  // 编辑
  if (id) {
    const currentSchool = schoolStore.currentSchool;
    if (currentSchool) {
      Object.assign(formState, currentSchool);
      formState.sxgfsd = formState.sxgfsd.split('-');
      formState.xxgfsd = formState.xxgfsd.split('-');
    }
  }
});

const schoolNameOptions = ref<any[]>([]);
const schoolNameLoading = ref(false);

// 处理学校名称搜索
const handleSchoolNameSearch = debounce(async (value: string) => {
  if (!value) {
    schoolNameOptions.value = [];
    return;
  }

  schoolNameLoading.value = true;
  try {
    const response = await Api.getGis({ schoolName: value });
    schoolNameOptions.value = response.map((item: any) => ({
      value: item.schoolName,
      label: item.schoolName,
      ...item,
    }));
  } catch (error) {
    message.error("获取学校信息失败");
  } finally {
    schoolNameLoading.value = false;
  }
}, 500);

// 处理学校名称选择
const handleSchoolNameSelect = (value: string, option: any) => {
  const [lng, lat] = option.gps84.split(",").map(Number);
  formState.jd1 = lng;
  formState.wd = lat;
  formState.dz = option.address;
};
</script>

<style scoped>
.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.back-button {
  font-size: 16px;
  padding: 0;
  margin-right: 16px;
  display: flex;
  align-items: center;
}

.page-title {
  margin-bottom: 0;
}

.form-card {
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
}

.form-actions {
  margin-top: 24px;
  text-align: center;
}

.action-button {
  margin-right: 16px;
}

:deep(.ant-form-item) {
  margin-bottom: 24px;
}

:deep(.ant-input-number) {
  width: 100%;
}
</style>
